import * as bomApi from '@/api';
import { IPlank } from '@/types';
import { OrderDetail } from '@/types/bom';
import { getDateSet, json2xlsx_export } from '@/utils/xlsx';
import { Upload } from 'antd';
import FileSaver from 'file-saver';
import { get, merge } from 'lodash-es';
import { useEffect, useState } from 'react';
import { useLocalStorage } from 'react-use';
import FetchData from './components/FetchData';

type Config = Record<string, string>;
type FieldConfigItem = {
  title: string;
  dataIndex: string;
};

const fieldConfig: FieldConfigItem[] = [
  {
    title: '序号',
    dataIndex: 'index',
  },
  {
    title: '编码',
    dataIndex: 'code',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '数量',
    dataIndex: 'count',
  },
  {
    title: '长mm（成型）',
    dataIndex: 'finishedWidth',
  },
  {
    title: '宽mm（成型）',
    dataIndex: 'finishedHeight',
  },
  {
    title: '厚mm',
    dataIndex: 'thickness',
  },
  {
    title: '材料/颜色',
    dataIndex: 'material+baseMaterial+thickness',
  },
  {
    title: '封边',
    dataIndex: 'edgeBanding',
  },
  {
    title: '长mm（开料）',
    dataIndex: 'cuttingWidth',
  },
  {
    title: '宽mm（开料）',
    dataIndex: 'cuttingHeight',
  },
  {
    title: '纹理方向',
    dataIndex: 'texture',
  },
  {
    title: '订单编号',
    dataIndex: 'orderNo',
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
  },
  {
    title: '房间名称',
    dataIndex: 'roomName',
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
  },
  {
    title: '客户地址',
    dataIndex: 'customerAddr',
  },
];

const edgeBandingConfig: Config = {
  '0,0,0,0': '无封边',
  '1,1,1,1': '全1',
  '0.5,0.5,0.5,0.5': '全0.5',
  '0.5,0.5,0.5,1': '三薄一厚',
};

const textureConfig: Config = {
  横纹: '0',
  竖纹: '90',
  无纹理: '0',
};

const configExported = {
  isExportNoRect: false,
  fieldConfig,
  'material+baseMaterial+thickness': {
    order: ['material', 'baseMaterial', 'thickness'],
  },
  edgeBandingConfig,
};

enum FileType {
  CSV = 'csv',
  XLS = 'xls',
}

type ConfigExported = Record<string, any>;
type FetchDataResult = (IPlank & OrderDetail)[];
function exportXLSX(
  data: FetchDataResult,
  type: FileType,
  config = configExported,
) {
  const result = data
    .filter((item) => {
      const { finishedProfile } = item;
      if (config.isExportNoRect) {
        return true;
      }
      if (!finishedProfile) {
        return true;
      }
    })
    .map((item, index) => {
      index++;
      const result = {};
      const count = 1;
      const { edgeBanding, texture } = item;
      const edgeBandingResult =
        config.edgeBandingConfig[edgeBanding?.toString()] ?? '异形';
      const textureResult = textureConfig[texture];
      const material$baseMaterial$thickness = config[
        'material+baseMaterial+thickness'
      ].order
        .map((field) => {
          return get(item, field);
        })
        .join('_');

      merge(result, item, {
        index,
        count,
        'material+baseMaterial+thickness': material$baseMaterial$thickness,
        // `${material}_${baseMaterial}_${thickness}`,
        edgeBanding: edgeBandingResult,
        texture: textureResult,
      });

      return result;
    });
  const dataSet = getDateSet(result, config.fieldConfig);
  console.log({ dataSet });
  json2xlsx_export(dataSet, `BOM_${Date.now()}.${type}`);
}

export default function IndexPage() {
  const [data, setData] = useState<any[]>([]);
  const [config, setConfig] = useLocalStorage(
    '@bom-export/config',
    configExported,
  );

  function handleExportConfig() {
    const content = JSON.stringify(config, null, 4);
    const blob = new Blob([content]);
    FileSaver.saveAs(blob, 'BOM_export-config.txt');
  }

  async function handleImportConfig(file: File) {
    const text = await file.text();
    const config = JSON.parse(text);
    setConfig(config);
  }

  useEffect(() => {
    // handleExport(data, FileType.XLS);
  }, [data]);

  function handleExportXLSX(fileType: FileType) {
    exportXLSX(data, fileType, config);
  }

  return (
    <div>
      <FetchData
        onConfirm={async (selected) => {
          // log({ selected });
          const bom = selected;
          const orderId = String(bom.id);
          const order = await bomApi.getOrderDetail(orderId);
          const result = bom.data.map((plank) => {
            return merge({}, plank, order);
          });
          setData(result);
        }}
      />
      <button onClick={() => handleExportXLSX(FileType.CSV)}>导出csv</button>
      <button onClick={() => handleExportXLSX(FileType.XLS)}>导出xls</button>
      <button onClick={() => handleExportConfig()}>导出配置文件</button>
      <Upload
        style={{ display: 'inline-block' }}
        showUploadList={false}
        beforeUpload={(file) => {
          handleImportConfig(file);
          return false;
        }}
        maxCount={1}
      >
        <button>导入配置文件</button>
      </Upload>
      <h1>导出xls可能需要较长时间,请耐心等候</h1>
    </div>
  );
}
